<template>
  <div class="attend_detail">
    <div class="attend_detail_left">
      <div class="info_detail_title">
        <div class="back" v-if="detailInfo.returnReason">
          <el-popover
            placement="right-start"
            title="退回原因"
            width="200"
            trigger="hover"
            :content="detailInfo.returnReason">
            <!-- <span>退回</span> -->
            <el-button type="danger" plain slot="reference" size="mini">已退回</el-button>
          </el-popover>
        </div>
        <div class="title_name">{{ detailInfo.overtimeTitle }}</div>
        <div class="title_box">
          <div class="title_org">部门：{{ detailInfo.orgName }}</div>
          <!-- <div class="title_tip">
            提示：值班时长4小时内或无打卡记录的，不享受调休与餐费补贴；4小时≤值班时长＜8小时的，可领取1份餐补；值班时长≥8小时的，可领取2份餐补。
          </div> -->
        </div>
      </div>
      <div class="right_box">
        <div class="attend_main">
          <div class="table_con" ref="table_con">
            <vxe-table
              border
              stripe
              class="mytable-scrollbar"
              highlight-hover-row
              size="medium"
              height="100%"
              :data="tableData"
              align="center"
              v-if="!load"
              @cell-click="cellClick"
              :span-method="mergeRowMethod"
              :edit-config="{ trigger: 'click', mode: 'row', activeMethod: activeRowMethod }"
              :empty-text="activeInfo.saveStatus === '1' ? '无人员值班' : '暂无确认'">
              <vxe-table-column field="overtimeDay" title="日期" width="300">
                <template #default="{ row }">
                  <span>{{ row.overtimeDay }}（{{ row.dayOfWeek }}）</span>
                </template>
              </vxe-table-column>
              <vxe-table-column field="timeBucket" title="时段" width="120">
                <template #default="{ row }">
                  <span>{{ row.timeBucket | TimeBucket }}</span>
                </template>
              </vxe-table-column>
              <vxe-table-column title="值班人员" width="200" :edit-render="{}">
                <template #default="{ row }">
                  <span>{{ memberDeal(row.userId) }}</span>
                </template>
                <template #edit="{ row }">
                  <el-select
                    v-model="row.userId"
                    filterable
                    placeholder=""
                    @change="roleChangeEvent(row)"
                    :popper-append-to-body="false"
                    size="small"
                    clearable="">
                    <el-option
                      :value="item.userId"
                      :label="item.userName"
                      v-for="item in showMemberList"
                      :key="item.userId"></el-option>
                  </el-select>
                  <!-- <vxe-select v-model="row.userId" clearable transfer @change="roleChangeEvent(row)">
                    <vxe-option
                      :value="item.userId"
                      :label="item.userName"
                      v-for="item in showMemberList"
                      :key="item.userId"
                    ></vxe-option>
                  </vxe-select> -->
                </template>
              </vxe-table-column>
              <vxe-table-column field="isLieu" title="是否调休" width="140">
                <template #default="{ row }">
                  <el-radio-group
                    v-model="row.isLieu"
                    :disabled="detail.saveStatus === '1'"
                    @change="lieuChange(row.isLieu)">
                    <el-radio label="1">是</el-radio>
                    <el-radio label="0">否</el-radio>
                  </el-radio-group>
                </template>
              </vxe-table-column>
              <!-- <vxe-table-column title="实际打卡时间" min-width="140">
                <template #default="{ row }">
                  <span v-if="row.punchStartTime || row.punchEndTime">
                    {{ row.punchStartTime }}-{{ row.punchEndTime }}
                  </span>
                  <span v-if="row.punchDuration">（{{ row.punchDuration }}）</span>
                </template>
              </vxe-table-column>
              <vxe-table-column title="加班补助" min-width="100">
                <template #default="{ row }">
                  <span v-if="row.subsidyStandard && row.isLieu === '0' && !showRadio(row)">
                    {{ row.subsidyStandard === '2' ? '两餐' : row.subsidyStandard === '1' ? '一餐' : '' }}
                  </span>
                  <el-radio-group v-model="row.subsidyStandard" v-if="showRadio(row)" @change="radioChange(row)">
                    <el-radio label="1">一餐</el-radio>
                    <el-radio label="2">两餐</el-radio>
                  </el-radio-group>
                </template>
              </vxe-table-column> -->
              <vxe-table-column field="remark" title="备注" min-width="140">
                <template #default="{ row }">
                  <span v-if="row.isLieu === '0'">{{ row.remark }}</span>
                </template>
              </vxe-table-column>
            </vxe-table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import {
  getWeekendDutyDetail,
  submitWeekendDuty,
  exportWeekendDutyExcel,
  getUserPunchInfo,
} from '@apis/api-dailyManage.js'
import moment from 'moment'
export default {
  components: {},
  props: {
    firstType: {
      type: String,
      default: '',
    },
    activeInfo: {
      type: Object,
      default: () => {},
    },
    memberList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      moment: moment,
      applyType: '1',
      timeNow: moment().format('YYYY-MM-DD'),
      model: '',
      reason: '',
      detail: {},
      detailInfo: {},
      dialogShow: false,
      suggest: '',
      tableData: [],
      load: false,
      activeData: {},
      showMemberList: [],
    }
  },
  computed: {
    memberActive() {
      if (this.memberList && this.memberList.length && this.activeInfo && this.activeInfo.id) {
        return true
      } else {
        return false
      }
    },
  },
  watch: {
    memberActive: {
      handler(news) {
        if (news) {
          this.showMemberList = this.memberList
          this.detail = this.activeInfo
          this.getWeekendDutyDetail()
        }
      },
      deep: true,
      immediate: true,
    },
  },
  filters: {
    TimeBucket(val) {
      switch (val) {
        case '0':
          return '全天'
        case '1':
          return '上午'
        case '2':
          return '下午'
        default:
          break
      }
    },
  },
  created() {},
  mounted() {
    if (this.$route.query.id && this.$route.query.type === '2') {
      this.detail = this.$route.query
      this.getWeekendDutyDetail()
    }
  },
  methods: {
    getWeekendDutyDetail() {
      getWeekendDutyDetail({
        id: this.detail.id,
      }).then(res => {
        if (res.code === 0) {
          this.detailInfo = res.data
          const data = res.data.itemDetailList || []
          data.forEach(item => {
            if (item.userId === '无') {
              item.userId = ''
            }
          })
          this.tableData = data
        }
      })
    },
    // 通用行合并函数（将相同多列数据合并为一行）
    mergeRowMethod({ row, _rowIndex, column, visibleData }) {
      const fields = ['overtimeDay']
      const cellValue = row.overtimeDay + row.dayOfWeek
      if (fields.includes(column.property)) {
        const prevRow = visibleData[_rowIndex - 1]
        let nextRow = visibleData[_rowIndex + 1]
        if (prevRow && prevRow.overtimeDay + prevRow.dayOfWeek === cellValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (nextRow && nextRow.overtimeDay + nextRow.dayOfWeek === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex]
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 }
          }
        }
      }
    },
    roleChangeEvent(row) {
      if (!row.userId) {
        const data = {
          punchStartTime: '',
          punchEndTime: '',
          punchDuration: '',
          amount: '',
          hours: '',
          subsidyStandard: '',
        }
        row = Object.assign(row, data)
        return
      }
      getUserPunchInfo({
        date: row.overtimeDay,
        userId: row.userId,
      }).then(res => {
        if (res.code === 0) {
          row = Object.assign(row, res.data)
        }
      })
    },
    // 设置是否可以编辑
    activeRowMethod({ row, rowIndex }) {
      if (this.detail.saveStatus !== '1') {
        return true
      }
    },
    cellClick({ row, column }) {
      if (this.detail.saveStatus === '1') return
      if (this.activeData.id === row.id) return
      this.activeData = row
      const arr = this.tableData.filter(item => {
        if (item.overtimeDay === this.activeData.overtimeDay && item.id !== this.activeData.id) {
          return true
        } else {
          return false
        }
      })
      const choose = []
      arr.forEach(item => {
        choose.push(item.userId)
      })
      const prepare = this.memberList.filter(item => {
        return !choose.includes(item.userId)
      })
      this.showMemberList = prepare
    },
    memberDeal(val) {
      if (!this.memberList.length) return
      const arr = this.memberList.filter(item => {
        return item.userId === val
      })
      return arr[0] && arr[0].userName
    },
    submit(type) {
      // if (type === '1') {
      //   const arr = this.tableData.filter(item => {
      //     return item.userId && Number(item.hours) < 4
      //   })
      //   if (arr.length > 0) {
      //     return this.$message.warning('值班时长4小时内或无打卡记录的，不享受调休与餐费补贴 ，请删除后再次确认提交')
      //   }
      // }

      const data = this.tableData
      data.forEach(item => {
        const arr = this.memberList.filter(li => {
          return li.userId === item.userId
        })
        item.userName = (arr[0] && arr[0].userName) || '无'
      })
      submitWeekendDuty({
        id: this.detail.id,
        saveStatus: type,
        weekendDutyDetailList: data,
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('成功')
          if (type === '1') {
            this.$emit('addSuccess', 'detail')
          }
        }
      })
    },
    exportData() {
      if (!this.detail.id) return
      const req = `?id=${encodeURIComponent(this.detail.id)}`
      const link = document.createElement('a')
      link.target = 'targetName'
      link.href = exportWeekendDutyExcel(req)
      link.click()
      link.remove()
    },
    showRadio(row) {
      if (this.detail.saveStatus !== '1' && row.subsidyStandard && row.isLieu === '0' && row.hours >= 8) {
        return true
      } else {
        return false
      }
    },
    lieuChange(type) {
      console.log('type :>> ', type)
    },
    radioChange(row) {
      if (row.subsidyStandard === '1') {
        row.remark = '一半调休，一半补助'
        row.amount = '40'
      } else {
        row.remark = ''
        row.amount = '80'
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.attend_detail {
  height: 100%;
  font-size: 16px;
  display: flex;
  .attend_detail_left {
    height: 100%;
    width: 100%;
  }
  .info_detail_title {
    font-weight: 400;
    padding-left: 20px;
    position: relative;
    // text-align: center;
    .title_name {
      text-align: center;
      height: 50px;
      line-height: 50px;
      font-size: 24px;
    }
    .title_org {
      font-weight: 600;
    }
    .title_box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-right: 20px;

      .title_tip {
        color: #be3a3c;
        font-size: 14px;
        max-width: 35%;
      }
      .title_org {
        margin-right: 20px;
        word-break: keep-all;
        flex-basis: initial;
        white-space: nowrap;
      }
    }
    .back {
      position: absolute;
      left: 20px;
      top: 10px;
      color: #be3a3c;
      cursor: pointer;
    }
  }
  .right_box {
    height: calc(100% - 130px);
    width: 100%;
    display: flex;
    flex-direction: column;
    margin-top: 10px;
    .attend_main {
      width: 100%;
      padding: 0 20px;
      height: calc(100% - 60px);
      margin: 0 auto;
      flex: 1;
    }
    .table_con {
      height: 100%;
      /deep/.vxe-cell--edit-icon {
        display: none;
      }
      /deep/.el-radio-group {
        display: flex;
        justify-content: space-around;
        align-items: center;
      }
    }
    .btn_check {
      margin-top: 10px;
      margin-right: 10px;
      text-align: center;
    }
  }
  .size_input {
    ::-webkit-outer-spin-button,
    ::-webkit-inner-spin-button {
      margin: 0;
      -webkit-appearance: none !important;
    }

    input[type='number']::-webkit-outer-spin-button,
    input[type='number']::-webkit-inner-spin-button {
      margin: 0;
      -webkit-appearance: none !important;
    }
  }
}
.branch_dialog {
  /deep/.el-dialog__body {
    padding-left: 20px;
    padding-right: 20px;
    min-height: 0;
    .el-radio {
      margin-right: 20px;
    }
    .el-textarea {
      margin: 20px 0;
    }
    .btn_save {
      text-align: right;
    }
  }
}
</style>
